<?php
define('STIME',microtime(true));
require_once '../includes/base.php';
$base = new Base();
require_once './install.lang.utf8.inc';
header('Content-type: text/html; charset='.CHARSET);

error_reporting(7);
global $_G;
$sqlfile = BASE_ROOT.'./install/install.sql';
$lockfile = BASE_ROOT.DATA_DIR.'./instal.lock';
file_exists($lockfile) && exit($lang['remove_install_lock']);
!file_exists($sqlfile) && exit($lang['install_file_noexist']) ;
$step = $_POST['step']?trim($_POST['step']):trim($_GET['step']);
empty($step) && $step = '1';

if($step == '1') {
	$accessfile['name'] = BASE_ROOT.'data';
	$accessfile['access'] = $lang['file_writable'];
	if(iswriteable($accessfile['name'])) {
        $accessfile['currently'] = '<span class="font_3">'.$lang['file_writable'].'</span>';
     }else{
     	$accessfile['currently'] = $lang['file_no_writable'];
     }
     $accessfiles[] = $accessfile;
} elseif($step == '2') {
	if(!isset($_POST['datadir'])) {
        	$data_dir = substr(DATA_DIR,5,-1);
     }
} elseif($step == '3') {
    if(!$_POST['system_exists_confirm']) {
        $dns = array();
        if(!$db_host = trim($_POST['dbhost']))    $error = '<li>'.$lang['needed_database_server'].'</li>';
        if(!$db_user = trim($_POST['dbuser']))    $error .= '<li>'.$lang['needed_database'].'</li>';
        $db_pass = trim($_POST['dbpass']);
        $db_port = trim($_POST['dbport']) ;
        if(trim($_POST['datadir']))$data_dir=trim($_POST['datadir']).'/';
        $data_dir = 'data/'.$data_dir ;
	    if (@is_dir(BASE_ROOT.$data_dir) === false) {
		    if(!@mkdir(BASE_ROOT.$data_dir,0777)) {
		    	die('目录'.$data_dir.'无法创建，请手动创建');
		    }
		}
		//附件目录
		if (@is_dir(BASE_ROOT.$data_dir.'files') === false) {
		    @mkdir(BASE_ROOT.$data_dir.'files',0777);
		}
		//缓存目录
		if (@is_dir(BASE_ROOT.$data_dir.'cache') === false) {
		    @mkdir(BASE_ROOT.$data_dir.'cache',0777);
		}
		//日记目录
		if (@is_dir(BASE_ROOT.$data_dir.'logs') === false) {
		    @mkdir(BASE_ROOT.$data_dir.'logs',0777);
		}
		//头像目录
		if (@is_dir(BASE_ROOT.$data_dir.'avatar') === false) {
		    @mkdir(BASE_ROOT.$data_dir.'avatar',0777);
		}
        if(!$db_name = trim($_POST['dbname']))    $error .= '<li>'.$lang['needed_database_username'].'</li>';
        if(strstr($_POST['dbpre'], '.'))                  $error .= '<li>'.$lang['databse_prefix_error'].'</li>';

        $curr_os = PHP_OS;
        $curr_php_version = PHP_VERSION;
        if($curr_php_version < '4.3.0')                 $error .= '<li>'.$lang['phpversion_error'].'</li>';
		
        $db_prefix = trim($_POST['dbpre']);
        
        
	  	if( !$error ) {
	  		$link = @mysql_connect($db_host,$db_user,$db_pass);
	  		if(!$link) {
        		$error .= '<li>'.$lang['cannot_connect_database'].'</li>';
        	}
	  		
	        if (!$error && !mysql_select_db($db_name, $link) ) {
		        if (!$error && !mysql_query("CREATE DATABASE ".$db_name) ) {
					$error .= '<li>'.$lang['cannot_create_database'].$db_name.'</li>';
				}else if(!mysql_select_db($db_name, $link)) {
					$error .= '<li>'.$lang['database_noexist'].'</li>';
				}
			}
	  	}
        if(!$error) {
			$settings_file = BASE_ROOT.$base->_get_setting_file();
			
          	$buffer = NULL;
		  	$first = TRUE;
		  	if ($fp = @fopen($settings_file, 'r+')) {
				$content = fread($fp, filesize($settings_file));
				fclose($fp);
				$content = preg_replace("/define\('DB_HOST','(.*?)'\);/is", "define('DB_HOST','$db_host');", $content);
				$content = preg_replace("/define\('DB_USER','(.*?)'\);/is", "define('DB_USER','".encrypt($db_user,$db_name)."');", $content);
				$content = preg_replace("/define\('DB_PASS','(.*?)'\);/is", "define('DB_PASS','".encrypt($db_pass,$db_name)."');", $content);
				$content = preg_replace("/define\('DB_NAME','(.*?)'\);/is", "define('DB_NAME','$db_name');", $content);
				$content = preg_replace("/define\('DB_PREFIX','(.*?)'\);/is", "define('DB_PREFIX','$db_prefix');", $content);
				$content = preg_replace("/define\('DATA_DIR','(.*?)'\);/is", "define('DATA_DIR','$data_dir');", $content);
				
				file_put_contents($settings_file, $content);
				
		  	} else {
                 exit($lang['configfile_write_error'].':'.$settings_file);
            }
			//判断数据库是否已有数据
            $system_exists = FALSE;

        }

        if($error) {
        	$step = 2;
        	$data_dir = substr($data_dir,5,-1);
        }
    }
} elseif($step == '4') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $password2 = trim($_POST['password2']);

    $error = install_check_username($username,$lang);
    $error .= install_check_email($email,$lang);
    $error .= install_check_password($password,$password2,$lang);

    if($fp = fopen($sqlfile, 'rb'))  {
        $sql = fread($fp, 2048000);
        fclose($fp);
    } else {
        exit($lang['configfile_write_error'].':'.$sqlfile);
    }

    if($error) {
        $step = 3;
    } else {
    	$base->_init_db();
    	$sql = strtr($sql, array('{{' => DB_PREFIX, '}}' => ''));
        $_G['db']->query("set names utf8");
	    $ret = array();
		$num = 0;
		foreach(explode(";\n", trim($sql)) as $query) {
			$queries = explode("\n", trim($query));
			foreach($queries as $query) {
				$ret[$num] .= $query[0] == '#' ? '' : $query;
			}
			$num++;
		}
		unset($sql);
	
		foreach($ret as $query) {
			$query = trim($query);
			if($query) {
				$_G['db']->query($query);
			}
		}
		$authkey = random(5);
		$_G['db']->insert('users',array('username' => $username,'password' => password($password,$authkey),'groupid'=>1,'status' => 1,'email' => $email,'regtime' => time(),'authkey' => $authkey));

        $fp = fopen($lockfile, 'x+');
        fclose($fp);
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET?>" />
<title><?php echo $lang['system_name']?></title>
<link href="<?php echo BASE_URL;?>install.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="main">
<form method="post" action="<?php echo $_VAR['php_self'];?>">
<h1 id="subject">
    <span id="title"><?php echo $lang['system_name'];?></span>
    <div class="clear"></div>
</h1>
<?php if($step == 1) { ?>
<div id="step"><?php echo $lang['step1'];?></div>
<?php if($error) {?><div id="error"><?php echo $error?></div><?php } ?>
<div>
<table>
    <tr id="tbth">
        <td width="60%"><?php echo $lang['dirname'];?></td>
        <td width="20%" align="center"><?php echo $lang['needed_status']?></td>
        <td width="20%" align="center"><?php echo $lang['current_status']?></td>
    </tr>
    <?php foreach($accessfiles as $accessfile) { ?>
    <tr><td><?php echo $accessfile['name']?></td><td align="center"><?php echo $accessfile['access']?></td><td align="center"><?php echo $accessfile['currently']?></td></tr>
    <?php } ?>
</table>
<div id="comment"><?php echo $lang['notice']?></div>
<input type="hidden" name="step" value="2" />
</div>
<?php } elseif($step == 2) { ?>
<div id="step"><?php echo $lang['step2']?></div>
<?php if($error) {?><div id="error"><?php echo $error?></div><?php } ?>
<table>
    <tr id="tbth"><td width="200"><?php echo $lang['item']?></td><td width="260"><?php echo $lang['value']?></td><td width="*"><?php echo $lang['description']?></td></tr>
    <tr><td><?php echo $lang['database_url']?>:</td><td><input type="text" name="dbhost" value="<?php echo $db_host;?>" /></td><td><?php echo $lang['localhost']?></td></tr>
    <tr><td><?php echo $lang['database_name']?>:</td><td><input type="text" name="dbname" value="<?php echo $db_name;?>" /></td><td><?php echo $lang['create_database_before_install']?></td></tr>
    <tr><td><?php echo $lang['database_username']?>:</td><td><input type="text" name="dbuser" value="<?php echo $db_user;?>" /></td><td></td></tr>
    <tr><td><?php echo $lang['database_password']?>:</td><td><input type="password" name="dbpass" value="<?php echo $db_pass;?>" /></td><td></td></tr>
    <tr><td><?php echo $lang['table_prefix']?>:</td><td><input type="text" name="dbpre" value="<?php echo $db_prefix;?>" /></td><td><?php echo $lang['multi_database_desc']?></td></tr>
	<tr><td><?php echo $lang['data_dir']?>:</td><td><input type="text" name="datadir" value="<?php echo $data_dir;?>" /></td><td><?php echo $lang['data_dir_desc']?></td></tr>
	
</table>
<div id="comment"><?php echo $lang['notice']?></div>
<input type="hidden" name="step" value="3" />
<?php } elseif($step == 3) { ?>
<?php if($system_exists) { ?>
<div id="error"><?php echo $lang['warning']?></div>
<input type="hidden" name="system_exists_confirm" value="true" />
<input type="hidden" name="step" value="3" />
<?php } else { ?>
<div id="step"><?php echo $lang['step3'];?></div>
<?php if($error) { ?><div id="error"><?php echo $error?></div><?php } ?>
<table>
    <tr id="tbth"><td width="200"><?php echo $lang['item']?></td><td width="260"><?php echo $lang['value']?></td><td width="*"><?php echo $lang['description']?></td></tr>
    <tr><td><?php echo $lang['admin']?>:</td><td><input type="text" name="username" value="admin" /></td><td><?php echo $lang['admin_desc']?></td></tr>
    <tr><td><?php echo $lang['email']?>:</td><td><input type="text" name="email" value="admin@yourdomain.com" /></td><td></td></tr>
    <tr><td><?php echo $lang['admin_password']?>:</td><td><input type="text" name="password" /></td><td></td></tr>
    <tr><td><?php echo $lang['repassword']?>:</td><td><input type="text" name="password2" /></td><td></td></tr>
</table>
<div id="comment"><?php echo $lang['notice']?></div>
<input type="hidden" name="step" value="4" />
<?php } ?>
<?php } elseif($step == 4) { ?>
<div id="step"><?php echo $lang['step4']?></div>
<div id="msg"><?php echo $lang['install_succuess']?></div>
<div id="control"><?php echo $lang['admin']?>: <?php echo $username?><br /><?php echo $lang['admin_password']?>: <?php echo $password?><br /><br /><a href="<?php echo substr(BASE_URL,0,-8);?>admin.php"><?php echo $lang['admin_login']?></a><br /></div>
<?php } ?>
<?php if(is_numeric($step)) { ?>
<div id="next">
    <?php if($step >= 1 && $step <=3) { ?><button type="button" name="name" onclick="history.go(-1);">上一步</button>&nbsp;<?php } ?>
    <?php if($step >=1 && $step < 4) { ?><button type="submit" name="name"<?php echo $next_enable?>>下一步</button><?php } ?>
</div>
<?php } ?>
</form>
</div>
</body>
</html>
<?php
function install_redirect($msg,$url,$min) {

}

function install_check_username($username,$lang) {
    $error = '';
    if(!$username) {
        $error =$lang['needed_username']. '<br />';
    } elseif(strlen($username) < 2 || strlen($username) > 16) {
        $error = $lang['username_length'].'<br />';
    } elseif($username != addslashes($username)) {
        $error = $lang['username_spec'].'<br />';
    } else {
        $name_key = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n",'#','$','(',')','%','@','+','?',';','^');
        foreach($name_key as $value){
            if (strpos($username, $value) !== false){ 
                $error = "<p>".$lang['username_spec']."</p>";
            }
        }
    }
    return $error;
}

function install_check_email($email,$lang) {
    $error = '';
    if(!$email) {
        $error .= $lang['needed_email']. '<br />';
    } elseif(strlen($email) < 6 || strlen($email) > 60) {
        $error .= $lang['email_length']. '<br />';
    } elseif(!is_email($email)) {
        $error .= $lang['email_error']. '<br />';
    }
    return $error;
}

function install_check_password($password,$password2,$lang) {
    $error = '';
    if(!$password) {
        $error .= $lang['needed_admin_password'] .'<br />';
    }
    if($password != stripslashes($password)) {
        $error .= $lang['password_special_char']. '.<br />';
    }
    if($password != $password2) {
        $error .= $lang['password_confirm_error']. '<br />';
    }
    return $error;
}
?>